package entity;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;
import util.Validator;

public class ChargeRule {
	
	public String id;
	public String name;
	public String type;
	public Double hourFactor;
	public Double monthFactor;
	public String execDate;
	public String createTime;

	public List<String[]> query(String[] params) {
		List<Object> list = new ArrayList<>();
		String sql = "select id,name,type,hourFactor,monthFactor,execDate,createTime from pm_charge_rule where true ";
		if(Validator.isNotEmpty(params[0])){
			sql += "and name like concat('%',?,'%') ";
			list.add(params[0]);
		}
		sql += "order by createTime desc";
		try {
			List<String[]> records = DBUtil.query(sql, list.toArray(), 7);
			return records;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return new ArrayList<String[]>();
	}

	public boolean save() {
		String sql = "insert into pm_charge_rule(name,type,hourFactor,monthFactor,execDate,createTime) values"
				+" (?,?,?,?,?,date_format(now(),'%Y-%m-%d %T'))";
		Object[] paraArray = {name,type,hourFactor,monthFactor,execDate};
		try {
			int count = DBUtil.update(sql, paraArray);
			return count > 0;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return false;
	}
	
	public boolean loadEffective(String type,String date) {
		String sql = "select id,name,type,hourFactor,monthFactor,execDate,createTime from pm_charge_rule "
				+ "where type = ? and str_to_date(execDate, '%Y-%m-%d') <= str_to_date(?, '%Y-%m-%d') "
				+ "order by str_to_date(execDate, '%Y-%m-%d') desc "
				+ "limit 1";
		Object[] paraArray = {type,date};
		try {
			String[] record = DBUtil.queryOne(sql, paraArray, 7);
			id = record[0];
			name = record[1];
			type = record[2];
			hourFactor = Double.parseDouble(record[3]);
			monthFactor = Double.parseDouble(record[4]);
			execDate = record[5];
			createTime = record[6];
			return true;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return false;
	}
	
	public String computeMonthly(String parkId,String date,int quantity) {
		Park park = new Park();
		park.id = parkId;
		park.load();
		if (loadEffective(park.type, date)) {
			return String.format("%.2f元", quantity * monthFactor);
		}
		return "请配置收费规则!";
	}
	
	public String computeGeneral(String parkId,String date,double quantity) {
		Park park = new Park();
		park.id = parkId;
		park.load();
		if (loadEffective(park.type, date)) {
			return String.format("%.2f元", quantity * hourFactor);
		}
		return "请配置收费规则!";
	}

}
